package com.mmc.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.mmc.config.OssProperties;
import com.mmc.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;


/**
 * 作者：李嘉浩
 * 时间：2024-09-16-15:20
 * 功能：
 */
@Service
public class OssServiceImpl implements OssService {
    @Autowired
    private OssProperties ossProperties;


    @Override
    public String upload(InputStream inputStream, String originalFilename) {
// Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ossProperties.getEndpoing();

        // 填写Bucket名称，例如examplebucket。
        String bucketName = ossProperties.getBucketName();

        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        //文件夹
        String format = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));  // 文件夹
        //文件名
        String uuid= UUID.randomUUID().toString();
        //文件后缀
        String suffix=originalFilename.substring(originalFilename.lastIndexOf("."));
        //模块名
        String  method="dict";
        //完整文件名
        String objectName = method+"/"+ format+"/"+uuid+suffix;

        String accessKey = ossProperties.getAccessKey();
        String accessSecret = ossProperties.getAccessSecret();


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey,accessSecret);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
            // ossClient.putObject();
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "http://"+bucketName+"."+endpoint+"/"+objectName;
    }
}
